﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using Dune.Business.Domain.Content;
using Dune.Business.Domain.Forum;
using Dune.Business.Domain.Users;
using Dune.Business.Managers;
using Edge.Common;
using Edge.Common.ComponentModel;
using Edge.Common.DataUtils;
using Edge.Common.Services;
using Edge.Common.Utils;
using Dune.DAL.Common;
using Dune.DAL.Managers.Users;
using Edge.Business.Entities;
using Edge.DAL.Managers;
using NHibernate;
using NHibernate.Expression;

namespace Dune.DAL.Managers
{
    class NewsManager : AbstractManager<News, int, User>,  INewsManager
    {
        public ICollection<News> Find(FetchOptions fetchOptions, NewsFilter filter)
        {
            try
            {
                ICriteria criteria = CreateCriteria(fetchOptions);
                AddRestrictions(criteria, filter);
                return criteria.List<News>();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public int Count(NewsFilter filter)
        {
            ICriteria criteria = CreateCriteria();
            AddRestrictions(criteria, filter);
            criteria.SetProjection(Projections.RowCount());
            return (int)criteria.List()[0];
        }

        private void AddRestrictions(ICriteria criteria, NewsFilter filter)
        {
            if (!StringUtils.IsBlankOrNull(filter.GetText()))
            {
                criteria.Add(Expression.Disjunction()
                                 .Add(Expression.Like("Description", "%" + filter.GetText().Trim() + "%"))
                                 .Add(Expression.Like("Header", "%" + filter.GetText().Trim() + "%")));
            }

            if (filter.CreatedBy != null)
            {
                criteria.Add(Expression.Eq("CreatedBy", filter.CreatedBy));
            }
            criteria.Add(Expression.Between("CreateDate", filter.RegisterDateFrom, filter.RegisterDateTo));
        }
        
        public void AddLog(ChangeType newsType, object logObject, string text, Person person)
        {
            string header = person.Name + " " + EnumUtils.GetDescriptionAttribute(newsType).ToLower() + " " + ReflectionUtils.GetDescriptionAttribute(logObject.GetType()).ToLower();
            News news = new News(header,text,DateTime.Now,person);
            Save(news);
        }

    }
}